<script lang="tsx">
import type { PropType } from 'vue';
import { defineComponent, ref } from 'vue';
import { NTag } from 'naive-ui';
import type { TagColor } from 'naive-ui/es/tag/src/common-props';
import { isHexColor } from '@/utils/color';
import { getDictOptions } from '@/utils/dict';

export default defineComponent({
  name: 'DictTag',
  props: {
    type: {
      type: String as PropType<string>,
      required: true
    },
    value: {
      type: [String, Number, Boolean] as PropType<string | number | boolean>,
      required: true
    }
  },
  setup(props) {
    const dictData = ref<CommonType.DictOption>();
    const getDictObj = (dictType: string, value: string) => {
      const dictOptions = getDictOptions(dictType);
      dictOptions.forEach((dict: CommonType.DictOption) => {
        if (dict.value === value) {
          if (`${dict.colorType}` === 'default') {
            dict.colorType = 'info';
          }
          dictData.value = dict;
        }
      });
    };
    const rederDictTag = () => {
      if (!props.type) {
        return null;
      }
      // 解决自定义字典标签值为零时标签不渲染的问题
      if (props.value === undefined || props.value === null) {
        return null;
      }
      getDictObj(props.type, props.value.toString());
      // 添加标签的文字颜色为白色，解决自定义背景颜色时标签文字看不清的问题
      const tagColor: TagColor | undefined =
        dictData.value?.cssClass && isHexColor(dictData.value?.cssClass)
          ? {
              color: dictData.value?.cssClass,
              borderColor: dictData.value?.cssClass,
              textColor: '#fff' // 设置文字颜色为白色
            }
          : undefined;
      return (
        <NTag style={dictData.value?.cssClass ? 'color: #fff' : ''} type={dictData.value?.colorType} color={tagColor}>
          {dictData.value?.label}
        </NTag>
      );
    };
    return () => rederDictTag();
  }
});
</script>
